from unicodedata import name
from market import app
from flask import render_template,redirect,url_for,flash,get_flashed_messages,request
from market.models import Item,User
from market.forms import RegisterForm,LoginForm,PurchaseItemForm,SellItemForm
from market import db,login_manager
from flask_login import current_user, login_user,logout_user,login_required
#主页

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

@app.route("/")
@app.route("/home")
def home_page():
    return render_template('home.html')

# @app.route('/about/<username>')#which function handling all the requests that are arriving to this url
# def about_page(username):
#     return f"<h1>about page of {username}</h1>"

#商品页
@app.route("/market",methods=["GET","POST"])
@login_required#当进入market之前必须要login
def market_page():
    purchase_form=PurchaseItemForm()
    selling_form=SellItemForm()
    if request.method=="POST":
        #purchase item logic
        purchased_item=request.form.get('purchased_item')
        p_item_object=Item.query.filter_by(name=purchased_item).first()
        if p_item_object:
            if current_user.can_purchase(p_item_object):#判断能不能买得起
                p_item_object.buy(current_user)
                flash(f"Congratulations! You purchased { p_item_object.name }",category='success')
            else:
                flash(f"Unfortunately you do not have enough money to purchase {p_item_object}",category='danger') 
        #selling item logic
        sold_item =request.form.get('sold_item')
        s_item_object=Item.query.filter_by(name=sold_item).first()
        if s_item_object:
            if current_user.can_sell(s_item_object):
                s_item_object.sell(current_user)
                flash(f"Congratulations! You sold { s_item_object.name } back to market",category='success')
            else:
                flash(f"Something went wrong with selling {s_item_object}",category='danger') 
            return redirect(url_for('market_page'))
    if request.method=="GET":
        items = Item.query.filter_by(owner=None)
        owned_items=Item.query.filter_by(owner=current_user.id)
    return render_template("market.html", items = items,purchase_form=purchase_form,owned_items=owned_items,selling_form=selling_form)
#注册页
@app.route('/register',methods=['GET','POST'])
def register_page():
    form=RegisterForm()
    if form.validate_on_submit():#检验是否按下了submit button
        # print(form.username.data)
        # print(form.email_address.data)
        # print(form.password1.data)
        user_to_create = User(username=form.username.data,
                            email_address=form.email_address.data,
                            password=form.password1.data)#从form传递信息
        db.session.add(user_to_create)
        db.session.commit()#保存到数据库中
        login_user(user_to_create)
        flash(f'Account created success!You are now logged in as {current_user.username}',category='success')#current_user其实指向的就是user_to_create
        return redirect(url_for('market_page'))
        #不习惯直接使用url，而是使用url_for直接导入函数
    if form.errors != {}:
        for err_msg in form.errors.values():
            flash(f"There are some err:{err_msg}")
    return render_template('register.html',form=form)

@app.route('/login',methods=['GET','POST'])
def login_page():
    form=LoginForm()
    if form.validate_on_submit():
        attempted_user = User.query.filter_by(username=form.username.data).first()
        if attempted_user and attempted_user.check_password_correction(attempted_password=form.password.data):
            login_user(attempted_user)
            flash(f'Success!You are logger in as :{attempted_user.username}',category='success')
            return redirect(url_for('market_page'))
        else:
            flash("Username and password are not match!please try again",category='danger')
    return render_template('login.html',form=form)


@app.route('/logout')
def logout_page():
    logout_user()
    flash('you have been logout',category='info')
    return redirect(url_for('home_page'))
    